package top.maof.book.rank;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 过滤器链缺陷:
 * 扩展性好,但是key维护过于麻烦,初始化过于繁琐
 * 无法解决热点数据的条件查询
 */
public class HandleChain<T> implements Handle<T> {

    private List<Handle> handles = new ArrayList<>();

    private int addPosition = 0;

    private int subPosition = 0;


    // key生成方法
    public static String generateKey(String... keys) {
        StringBuilder sb = new StringBuilder(64);
        for (int i = 0; i < keys.length; i++) {
            if (keys[i] == null || "".equals(keys[i])) {
                continue;
            }
            sb.append(keys[i]);
            sb.append(":");
        }
        String key = sb.toString();
        if (key != null && key.length() > 0) {
            key = key.substring(0, key.length() - 1);
        }
        return key;
    }


    public void put(Handle... handles) {
        List<Handle> list = Arrays.asList(handles);
        this.handles.addAll(list);
    }


    public HandleChain put(Handle handle) {
        this.handles.add(handle);
        return this;
    }

    public HandleChain put(int index, Handle handle) {
        this.handles.add(index, handle);
        return this;
    }

    @Override
    public void add(T t, HandleChain handleChain) {
        // 处理器链执行完毕
        if (addPosition == handles.size()) {
            addPosition = 0;
            return;
        }
        this.handles.get(addPosition++).add(t, this);
    }

    @Override
    public void sub(T t, HandleChain handleChain) {
        // 处理器链执行完毕
        if (subPosition == handles.size()) {
            subPosition = 0;
            return;
        }
        this.handles.get(subPosition++).sub(t, this);
    }
}
